package com.credit.mola.app.ui.credit.activity

import android.annotation.SuppressLint
import android.graphics.Typeface
import android.os.CountDownTimer
import android.view.View
import android.widget.SeekBar
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.credit.mola.app.R
import com.credit.mola.app.adapter.AmountAdapter
import com.credit.mola.app.adapter.CreditApplyDaysAdapter
import com.credit.mola.app.databinding.CreditApplyBinding
import com.credit.mola.app.databinding.ItemCreditApplyDetailBrandBinding
import com.credit.mola.app.databinding.ItemCreditApplyDetailChildBinding
import com.credit.mola.app.pro.ProActivity
import com.credit.mola.app.utils.BarUtils
import com.credit.mola.app.utils.DensityUtils
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.event.EventType
import com.credit.mola.app.utils.event.track.TrackEventManager
import com.credit.mola.app.utils.helper.ActivityStackHelper
import com.credit.mola.app.utils.http.AppUrls
import com.credit.mola.app.utils.http.AppUrls.addCommonParams
import com.credit.mola.app.utils.http.IHttpCallback
import com.credit.mola.app.utils.rv.GridDecoration
import com.credit.mola.app.utils.rv.LinearDecoration
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/22 17:31
 * @Annotation：贷款申请
 */
class ApplyActivity: ProActivity() {
    private var _binding: CreditApplyBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    //金额
    private var mAmountAdapter: AmountAdapter? = null
    //老用户可以选择时间
    private var mDaysAdapter: CreditApplyDaysAdapter? = null

    //老客申请金额刻度
    private var mScale = 0
    private var mMinProcess = 0//最小值

    private var countdownTimer: MyCountDownTimer? = null
    //等待时长
    private var countdown = 10 * 60

    override fun getRootView(): View {
        _binding = CreditApplyBinding.inflate(layoutInflater)
        return binding.root
    }

    @Subscribe
    override fun initView() {
        _binding?.parentLayout?.setPadding(0,BarUtils.getStatusBarHeight(),0,0)
        initRefreshLayout()
        initRvAmount()
        initRvDays()

        _binding?.applyContentLayout?.visibility = View.INVISIBLE
        _binding?.applyApprovedLayout?.visibility = View.INVISIBLE
        _binding?.btnSubmit?.visibility = View.INVISIBLE
    }

    override fun initListener() {
        _binding?.imgBack?.setOnClickListener {
            finish()
        }
        _binding?.imgKefu?.setOnClickListener {
            showKefuDialog("CreditApply Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"CreditApply Page")
        }
        _binding?.seekBar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 当进度改变时调用
                val showProcess = progress * mScale + mMinProcess
                _binding?.textLimitAmount?.text = "$showProcess"
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                // 当用户开始触摸SeekBar（按下）时调用
            }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                // 当用户结束触摸SeekBar（抬手）时调用
                loadCreditApplyDataAction()
            }
        })
        //确定
        _binding?.btnSubmit?.setOnClickListener {
            showLoading()
            TrackEventManager.trackEventNow(EventType.CLICK.CLICK_CREDIT_APPLY_CONFIRM,"")
            //创建贷款订单
            onCreateApplyOrderAction()
        }
    }

    override fun initData() {
        showLoading()
        loadCreditApplyDataAction()
    }

    /* 初始化刷新 */
    private fun initRefreshLayout() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            loadCreditApplyDataAction()
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    /**
     * 金额列表
     */
    private fun initRvAmount(){
        _binding?.rvAmount?.setHasFixedSize(true)
        _binding?.rvAmount?.isNestedScrollingEnabled = false
        _binding?.rvAmount?.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(14f)
        _binding?.rvAmount?.addItemDecoration(LinearDecoration(0, decoration, 0, 0))
        val layoutManager = LinearLayoutManager(getContext())
        layoutManager.orientation = RecyclerView.HORIZONTAL
        _binding?.rvAmount?.layoutManager = layoutManager
        mAmountAdapter = AmountAdapter(_binding?.rvAmount)
        mAmountAdapter?.setOnItemChildClickListener { parent, childView, position ->
            val item = this.mAmountAdapter?.getItem(position)
        }
        _binding?.rvAmount?.adapter = mAmountAdapter
    }

    /**
     * 选择days列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initRvDays(){
        _binding?.rvDays?.setHasFixedSize(true)
        _binding?.rvDays?.isNestedScrollingEnabled = false
        _binding?.rvDays?.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(22f)
        _binding?.rvDays?.addItemDecoration(GridDecoration(3, decoration, false))
        val layoutManager = GridLayoutManager(getContext(),3)
        _binding?.rvDays?.layoutManager = layoutManager
        mDaysAdapter = CreditApplyDaysAdapter(_binding?.rvDays)
        mDaysAdapter?.setOnItemChildClickListener { parent, childView, position ->
            mDaysAdapter?.let {
                val item = it.getItem(position)
                if (item.optBoolean("isSelect",false)){
                    return@setOnItemChildClickListener
                }
                for (i in 0..< it.itemCount){
                    val model = it.getItem(i)
                    model.put("isSelect",false)
                    if (i == position){
                        model.put("isSelect",true)
                    }
                }
                it.notifyDataSetChanged()

                loadCreditApplyDataAction()
            }
        }
        _binding?.rvDays?.adapter = mDaysAdapter
    }

    /**
     * 设置贷款额度预览信息
     */
    fun setCreditApplyData(data: JSONObject) {
        showSikadwaAmountViews(data)
        showSikadwaDaysView(data)
        showSikadwaDataItemList(data)
        _binding?.applyContentLayout?.visibility = View.VISIBLE
        _binding?.applyApprovedLayout?.visibility = View.VISIBLE
        _binding?.btnSubmit?.visibility = View.VISIBLE
    }

    /**
     * 设置额度View
     */
    private fun showSikadwaAmountViews(data: JSONObject?){
        data?.let {
            val amount = BigDecimal(it.optString("amount")).stripTrailingZeros().toPlainString()
            _binding?.textLimitAmount?.text = amount
            //是否允许修改申请金额，不允许修改则不显示Seekbar
            val chooseAmountFlag = it.optBoolean("chooseAmountFlag",false)
            when(chooseAmountFlag){
                true -> {//可选额度
                    _binding?.newLimitLayout?.visibility = View.GONE
                    _binding?.oldLimitLayout?.visibility = View.VISIBLE
                    mMinProcess = BigDecimal(it.optString("minAmount")).stripTrailingZeros().toPlainString().toInt()
                    val maxAmount = BigDecimal(it.optString("maxAmount")).stripTrailingZeros().toPlainString()
                    //颗粒度
                    mScale = it.optInt("granularity")

                    _binding?.textMinLimit?.text = "$mMinProcess"
                    _binding?.textMaxLimit?.text = maxAmount
                    //设置最大值
                    val maxProcess = (maxAmount.toInt() - mMinProcess) / mScale
                    _binding?.seekBar?.max = maxProcess
                    //设置当前值
                    val showAmount = (amount.toInt() - mMinProcess) / mScale
                    _binding?.seekBar?.progress = showAmount
                }
                else -> {//不可选额度
                    _binding?.newLimitLayout?.visibility = View.VISIBLE
                    _binding?.oldLimitLayout?.visibility = View.GONE

                    val amountList = arrayListOf<String>()
                    for (i in amount.indices){
                        amountList.add(amount[i].toString())
                    }
                    mAmountAdapter?.data = amountList
                }
            }
        }
    }

    /**
     * 设置贷款时长View
     */
    private fun showSikadwaDaysView(data: JSONObject?){
        data?.let {
            if (mDaysAdapter?.itemCount == 0){
                //默认天数
                val defaultDays = data.optString("days")
                val daysArray = data.optJSONArray("daysArray")
                val dayList = arrayListOf<JSONObject>()
                if (daysArray != null) {
                    //如果daysArray中没有defaultDays，需要将defaultDays添加到daysArray列表中
                    var isNeedAdd = true
                    for (i in 0..<daysArray.length()){
                        if (daysArray.optString(i) == defaultDays){
                            isNeedAdd = false
                            break
                        }
                    }
                    if (isNeedAdd){
                        daysArray.put(0,defaultDays)
                    }

                    for (i in 0..<daysArray.length()){
                        val day = daysArray.optString(i)
                        val obj = JSONObject()
                        obj.put("day",day)
                        obj.put("isSelect",day == defaultDays)
                        dayList.add(obj)
                    }
                }
                mDaysAdapter?.data = dayList
                _binding?.textLoanTermDays?.text = String.format(getString(R.string.credit_apply_loan_term_days),defaultDays)
            }

            mDaysAdapter?.let { adapter ->
                if (adapter.itemCount > 1){
                    _binding?.newDaysLayout?.visibility = View.GONE
                    _binding?.oldDaysLayout?.visibility = View.VISIBLE
                    _binding?.rvDays?.visibility = View.VISIBLE
                } else {
                    _binding?.newDaysLayout?.visibility = View.VISIBLE
                    _binding?.oldDaysLayout?.visibility = View.GONE
                    _binding?.rvDays?.visibility = View.GONE
                }
            }
        }
    }

    /**
     * 设置明细
     */
    private fun showSikadwaDataItemList(data: JSONObject?){
        data?.let {
            //明细
            val array = it.optJSONArray("detailItemList")
            val detailItemList = arrayListOf<JSONObject>()
            array?.let { list ->
                for (i in 0..<list.length()){
                    val item = list.optJSONObject(i)
                    if (item.has("title") && item.optString("title") == "YES"){
                        detailItemList.add(item)
                    }
                }
                for (i in 0..<detailItemList.size){
                    val obj = detailItemList[i]
                    val childArray = JSONArray()
                    var isAddChild = false
                    for (n in 0..<list.length()){
                        val item = list.optJSONObject(n)
                        if (obj.optString("showName") == item.optString("showName")){
                            isAddChild = true
                            childArray.put(item)
                            continue
                        }
                        if (item.has("title") && item.optString("title") == "YES"){
                            isAddChild = false
                            continue
                        }
                        if (isAddChild){
                            childArray.put(item)
                        }
                    }
                    obj.put("childList",childArray)
                }
            }
            _binding?.dataItemListLayout?.removeAllViews()
            detailItemList.forEach { itemList ->
                val itemBinding = ItemCreditApplyDetailBrandBinding.inflate(layoutInflater)
                val childList = itemList.optJSONArray("childList")
                if (childList != null){
                    for (i in 0..<childList.length()){
                        val childItem = childList.optJSONObject(i)
                        val childView = ItemCreditApplyDetailChildBinding.inflate(layoutInflater)
                        childView.textDetailsTitle.text = childItem.optString("showName")
                        childView.textDetailsTitle.setTextColor(getColor(R.color.FF999999))
                        childView.textDetailsValue.text = childItem.optString("showDetail")
                        childView.textDetailsValue.setTextColor(getColor(R.color.black))

                        if (childItem.has("title") && childItem.optString("title") == "YES"){
                            childView.textDetailsTitle.typeface = Typeface.create(Typeface.DEFAULT,Typeface.BOLD)
                            childView.textDetailsTitle.setTextColor(getColor(R.color.black))
                            childView.textDetailsValue.typeface = Typeface.create(Typeface.DEFAULT,Typeface.BOLD)
                            childView.textDetailsValue.setTextColor(getColor(R.color.black))
                        }
                        childView.textOldValue.visibility = View.GONE
                        if (childItem.has("oldDetail")){
                            childView.textOldValue.visibility = View.VISIBLE
                            childView.textOldValue.text = childItem.optString("oldDetail")
                            childView.textDetailsValue.setTextColor(getColor(R.color.FFFF451F))
                        }
                        childView.discountLayout.visibility = View.GONE
                        if (childItem.has("discount")){
                            childView.discountLayout.visibility = View.VISIBLE
                            childView.textDiscount.text = childItem.optString("discount")
                        }
                        itemBinding.detailsBrandLayout.addView(childView.root)
                    }
                }
                _binding?.dataItemListLayout?.addView(itemBinding.root)
            }
        }
    }

    /**
     * 获取当前选中的期限
     */
    private fun getSelectDays(): String{
        var days = ""
        mDaysAdapter?.let {
            if (it.itemCount > 0){
                for (i in 0..< it.itemCount){
                    val item = it.getItem(i)
                    if (item.optBoolean("isSelect",false)){
                        days = item.optString("day")
                        break
                    }
                }
            }
        }
        return days
    }

    /**
     * 订单状态 或 申请状态 验证不通过，需要返回首页显示对应页面
     */
    private fun applyFailed() {
        ActivityStackHelper.finishAllActivity(CreditActivity::class.java)
    }

    /**
     * 开启倒计时
     */
    private fun startSikadwaApplyCountdownTimer(){
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        countdown = 10 * 60
        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown.toLong() * 1000, 1000)
        }
        countdownTimer?.start()
    }

    /**
     * 显示状态
     */
    private fun showSikadwaApplyCountdownText(){
        val seconds = countdown % 60
        val minutes = countdown / 60 % 60
        _binding?.textApplyCountdown?.text = String.format("%s:%s", if (minutes < 10) "0$minutes" else "$minutes", if (seconds < 10) "0$seconds" else "$seconds")
    }

    private fun showSikadwaApplyCountdownComplete(){
        startSikadwaApplyCountdownTimer()
        loadCreditApplyDataAction()
    }

    class MyCountDownTimer(private val act: ApplyActivity, millisInFuture: Long, countDownInterval: Long): CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showSikadwaApplyCountdownText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showSikadwaApplyCountdownComplete()
        }
    }

    /**
     * 贷款申请订单创建成功
     */
    fun createOrderSuccess() {
        hideLoading()
        //发送更新总流程通知
        EventBus.getDefault().post(Configs.Event.PROCESS_REFRESH)
        finish()
        //返回首页
        ActivityStackHelper.finishAllActivity(CreditActivity::class.java)
    }

    /**
     * 获取贷款信息
     */
    private fun loadCreditApplyDataAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams()
        params.put("path",AppUrls.PATH.CREDIT_APPLY_CUSTOM_LIMIT)
        params.put("amount",_binding?.textLimitAmount?.text.toString())
        if (getSelectDays().isNotEmpty()){
            params.put("days",getSelectDays())
        }
        params.put("oldFlag","YES")
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    setCreditApplyData(it)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                _binding?.refreshLayout?.finishRefresh()
            }
        })
    }

    /**
     * 创建订单
     */
    private fun onCreateApplyOrderAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.CREDIT_APPLY_ORDER_CREATE)
        }
        params.put("amount",_binding?.textLimitAmount?.text.toString())
        params.put("days",getSelectDays())
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                createOrderSuccess()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun onStart() {
        super.onStart()
        startSikadwaApplyCountdownTimer()
        addEvent(EventType.PAGE.PAGE_CREDIT_APPLY_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_CREDIT_APPLY_END,"")
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
        _binding = null
    }
}